// 使用 new origin.constructor() 创建对象或数组
// 使用WeakMap记录origin，解决无限递归问题

const obj = {
    a: 1,
    b: {
        c: {
            d: 1
        },
    },
    c: [1, 2, 4]
}


function deepClone(origin, target = {}) {
    const map = new WeakMap();
    const arr = [{origin, target}];
    if (origin === null) return null;
    let tar;
    while(tar = arr.shift()) {
        const {origin, target} = tar;
        for (let key in origin) {
            if (Object.hasOwnProperty.call(origin, key)) {
                if (typeof(origin[key]) === 'object' && origin[key] !== null) {
                    if (map.has(origin[key])) {
                        target[key]= map.get(origin[key]);
                    } else {
                        target[key] = new origin[key].constructor();
                        // deepClone(origin[key], target[key])
                        arr.push({origin: origin[key], target: target[key]});
                    }
                } else {
                    target[key] = origin[key];
                }
            }
        }
    }
    return target;
}
console.log(deepClone(obj));